<template>
  <div class="page-container">
    <div>
      <!-- 顶部标题栏 -->
      <header class="header">
     <el-button type="danger" class="logout-btn" @click="handleLogout">
            <el-icon><SwitchButton /></el-icon>
            退出登录
          </el-button>
        <h1>"码上巡察"举报系统后台管理页面</h1>
      
          <Time class="time-display" />

      </header>

      <!-- 主要内容区域 -->
      <div class="main-content" style="margin-top: -70px;">
        <!-- 搜索和筛选区域 -->
        <div class="search-section">
          <el-input v-model="searchText" placeholder="支持搜索被反映人、被反映单位" class="search-input">
            <template #append>
              <el-button type="primary" class="search-btn" @click="handleSearch">
                <el-icon class="search-icon">
                  <Search />
                </el-icon>
              </el-button>
            </template>
          </el-input>

          <div class="filter-section">
            <!-- 日期范围选择 -->
            <div class="date-range-picker">
              <el-date-picker v-model="dateRange[0]" type="date" placeholder="开始日期" class="date-picker"
                @change="handleFilterChange" />
              <span class="separator">—</span>
              <el-date-picker v-model="dateRange[1]" type="date" placeholder="结束日期" class="date-picker"
                @change="handleFilterChange" />
            </div>

            <!-- 时间选择 -->
            <el-select v-model="sortBy" placeholder="排序：提交时间(倒序)" @change="handleFilterChange">
              <el-option label="提交时间(倒序)" value="desc" />
              <el-option label="提交时间(正序)" value="asc" />
            </el-select>

            <!-- 状态筛选 -->
            <el-select v-model="types" placeholder="举报类型：全部" @change="handleFilterChange">
              <el-option label="举报类型：全部" value="all" />
              <el-option label="实名举报" value="实名举报" />
              <el-option label="匿名举报" value="匿名举报" />
            </el-select>

            <!-- 标签筛选 -->
            <el-select v-model="labels" placeholder="标签筛选：全部" @change="handleFilterChange">
              <el-option label="标签筛选：全部" value="all" />
              <el-option label="失职渎职嫌疑" value="失职渎职嫌疑" />
              <el-option label="行贿受贿嫌疑" value="行贿受贿嫌疑" />
              <el-option label="作风问题" value="作风问题" />
              <el-option label="其他问题" value="其他问题" />
            </el-select>

            <!-- 导出按钮放在右侧 -->
            <div class="export-btn-wrapper">
              <el-button type="danger" :loading="isExporting" @click="handleExcel">导出列表</el-button>
            </div>
          </div>
        </div>

        <!-- 表格区域 -->
        <div class="table-container">
          <div class="table-section">
            <div class="news-list" v-loading="loading" element-loading-text="加载中..."
              :element-loading-background="'rgba(0, 0, 0, 0)'">
              <!-- 添加表头 -->
              <div class="news-header">
                <div class="header-item main-issue">主要问题</div>
                <div class="header-item reported-unit">被反映人单位</div>
                <div class="header-item reported-person">被反映人姓名</div>
                <div class="header-item submit-time">提交时间</div>
                <div class="header-item report-type">举报类型</div>
                <div class="header-item department">分管部门</div>
                <div class="header-item action"></div>
              </div>

              <!-- 数据列表 -->
              <div v-for="(item, index) in tableData" :key="index" class="news-item">
                <div class="line"></div>
                <div class="news-info" @click="handleViewDetail(item)" style="cursor: pointer;">
                  <div class="info-value main-issue" :title="item.mainIssue">{{ item.mainIssue }}</div>
                  <div class="info-value reported-unit" :title="item.reportedUnit">{{ item.reportedUnit }}</div>
                  <div class="info-value reported-person" :title="item.reportedPerson">{{ item.reportedPerson }}</div>
                  <div class="info-value submit-time">{{ item.submitTime }}</div>
                  <div class="info-value report-type">{{ item.reportType }}</div>
                  <div class="info-value department">{{ item.department }}</div>
                </div>
                <div class="news-actions">
                  <el-button 
                    type="primary" 
                    class="download-btn" 
                    @click.stop="handleDownloadItem(item)"
                    :loading="downloadingItems[item.reportId]"
                  >
                    <el-icon class="download-icon"><Download /></el-icon>
                    下载
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination 
            :current-page="pageNum" 
            :page-size="pageSize" 
            :page-sizes="[3, 5, 10, 15]"
            :background="false" 
            layout="prev, pager, next, jumper" 
            :total="total" 
            @update:current-page="pageNum = $event"
            @update:page-size="pageSize = $event"
            @size-change="onSizeChange"
            @current-change="onCurrentChange" 
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'

import { useAdminStore } from '@/stores/admin.js'
import { useReportStore } from '@/stores/report.js'
import { useTokenStore } from '@/stores/token.js'
import { getReportDetail, downloadFile } from '@/api/report.js'
import { storeToRefs } from 'pinia'
import Time from '@/components/Time.vue'
import BackBtn from '@/components/Back-btn.vue'
import { Search, SwitchButton, Download } from '@element-plus/icons-vue'
import JSZip from 'jszip'
import { saveAs } from 'file-saver'
import { Document, Paragraph, TextRun, Packer } from 'docx'

const router = useRouter()
const route = useRoute()

const adminStore = useAdminStore()
const reportStore = useReportStore()
const tokenStore = useTokenStore()

// 初始化数据
const tableData = ref([])
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const dateRange = ref([null, null])
const types = ref('all')
const labels = ref('all')
const sortBy = ref('desc')
const searchText = ref('')
const loading = ref(false)
const downloadingItems = ref({}) // 用于跟踪每个条目的下载状态

// 从 adminStore 获取管理员信息
const { adminInfo } = storeToRefs(adminStore)
const { reports, total: reportTotal, loading: reportLoading } = storeToRefs(reportStore)

// 监听报表数据变化
watch(reports, (newVal) => {
  tableData.value = newVal
})

watch(reportTotal, (newVal) => {
  total.value = newVal
})

watch(reportLoading, (newVal) => {
  loading.value = newVal
})

// 计算属性：根据角色返回对应的部门标题
const departmentTitle = computed(() => {
  // 优先使用路由中的role参数
  const routeRole = route.query.role
  const role = routeRole !== undefined ? routeRole : adminInfo.value?.role
  
  const titleMap = {
    0: '-超级管理员',
    1: '-区医保局',
    2: '-区信访局',
    3: '-区教体局'
  }
  return titleMap[role] || ''
})

const isExporting = ref(false)

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化表格数据中的时间
const formatTableData = (data) => {
  if (!data) return []
  return data.map(item => ({
    ...item,
    createdAt: formatTime(item.createdAt),
    startTime: formatTime(item.startTime),
    endTime: formatTime(item.endTime),
    submitTime: formatTime(item.submitTime)
  }))
}

// 重置所有筛选条件的函数
const resetFilters = () => {
  searchText.value = ''  // 重置搜索文本
  dateRange.value = [null, null]  // 重置日期范围
  labels.value = 'all'  // 重置标签筛选
  types.value = 'all'  // 重置状态筛选
  sortBy.value = 'desc'  // 重置时间排序为默认的倒序
  pageNum.value = 1  // 重置页码
  pageSize.value = 10  // 重置每页条数
}

// 分页处理
const onSizeChange = async (size) => {
  pageSize.value = size
  await fetchData()
  tableData.value = formatTableData(tableData.value)
}

const onCurrentChange = async (num) => {
  pageNum.value = num
  await fetchData()
  tableData.value = formatTableData(tableData.value)
}

// 处理搜索
const handleSearch = async () => {
  pageNum.value = 1
  await fetchData()
  tableData.value = formatTableData(tableData.value)
}

// 筛选条件变化时的处理
const handleFilterChange = async () => {
  pageNum.value = 1
  await fetchData()
  tableData.value = formatTableData(tableData.value)
}

// 数据获取函数
const fetchData = async () => {
  // 处理日期范围转换为开始和结束日期字符串
  let startDate = ''
  let endDate = ''
  if (dateRange.value[0] && dateRange.value[1]) {
    startDate = dateRange.value[0].toISOString().split('T')[0]
    endDate = dateRange.value[1].toISOString().split('T')[0]
  }
  
  // 获取当前角色
  const routeRole = route.query.role
  const role = routeRole !== undefined ? routeRole : adminInfo.value?.role
  
  // 调用store获取数据
  await reportStore.fetchReports({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    searchText: searchText.value,
    startDate,
    endDate,
    sortType: sortBy.value,
    types: types.value === 'all' ? '' : types.value,
    labels: labels.value === 'all' ? '' : labels.value,
    role
  })
  tableData.value = formatTableData(tableData.value)
}

// 导出处理
const handleExcel = async () => {
  isExporting.value = true
  try {
    console.log('开始导出处理');
    // 处理日期范围转换为开始和结束日期字符串
    let startDate = ''
    let endDate = ''
    if (dateRange.value[0] && dateRange.value[1]) {
      startDate = dateRange.value[0].toISOString().split('T')[0]
      endDate = dateRange.value[1].toISOString().split('T')[0]
    }
    
    // 获取当前角色
    const routeRole = route.query.role
    const role = routeRole !== undefined ? routeRole : adminInfo.value?.role
    
    // 构建导出参数
    const exportParams = {
      searchText: searchText.value,
      startDate,
      endDate,
      sortType: sortBy.value,
      types: types.value === 'all' ? '' : types.value,
      labels: labels.value === 'all' ? '' : labels.value,
      role
    }
    
    console.log('导出参数:', exportParams);
    
    // 直接从API调用导出方法
    const response = await reportStore.exportReportsList(exportParams)
    
    console.log('导出成功');
    // 成功提示
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error);
    // 失败提示
    ElMessage.error(error.message || '导出失败')
  } finally {
    isExporting.value = false
  }
}

const handleViewDetail = (row) => {
  // 跳转到详情页，params 中带上 reportId
  console.log('查看详情:', row);
  router.push({ name: 'reportDetail', params: { reportId: row.reportId } })
}

// 处理退出登录
const handleLogout = () => {
  // 清除token
  tokenStore.removeToken()
  // 清除管理员信息
  adminStore.clearAdminInfo()
  // 提示用户
  ElMessage.success('退出登录成功')
  // 跳转到登录页面
  router.push('/login')
}

// 格式化标签
const formatTags = (tags) => {
  if (!tags) return '无'
  
  // 标签映射
  const tagMap = {
    'bribery': '行贿受贿嫌疑',
    'dereliction': '失职渎职嫌疑',
    'lifestyle': '作风问题',
    'other': '其他问题'
  }
  
  return tags.split(',').map(tag => tagMap[tag] || tag).join(', ')
}

// 格式化日期时间，更详细的格式
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      hour12: false
    })
  } catch (e) {
    return dateTimeStr
  }
}

// 附件大小格式化
const formatSize = (size) => {
  if (size === undefined || size === null) return ''
  
  if (size < 1024) return size + 'KB'
  return (size / 1024).toFixed(2) + 'MB'
}

// 生成Word文档
const generateWordDocument = async (report) => {
  try {
    // 创建文档
    const doc = new Document({
      sections: [{
        properties: {},
        children: [
          new Paragraph({
            children: [
              new TextRun({
                text: "举报详情",
                bold: true,
                size: 32,
              }),
            ],
            spacing: { after: 400 },
          }),
          // 基本信息
          new Paragraph({
            children: [new TextRun({ text: `举报类型：${report.reportType || '无'}`, size: 24 })],
            spacing: { after: 200 },
          }),
          
          // 实名举报才展示的字段
          ...(report.reportType === '实名举报' ? [
            new Paragraph({
              children: [new TextRun({ text: `举报人姓名：${report.reporterName || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            new Paragraph({
              children: [new TextRun({ text: `举报人身份证号：${report.reporterIdCard || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            new Paragraph({
              children: [new TextRun({ text: `举报人手机号：${report.reporterPhone || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
            new Paragraph({
              children: [new TextRun({ text: `举报人联系地址：${report.reporterAddress || '无'}`, size: 24 })],
              spacing: { after: 200 },
            }),
          ] : []),
          
          new Paragraph({
            children: [new TextRun({ text: `被反映人姓名：${report.reportedPerson || '无'}`, size: 24 })],
            spacing: { after: 200 },
          }),
          new Paragraph({
            children: [new TextRun({ text: `被反映人单位：${report.reportedUnit || '无'}`, size: 24 })],
            spacing: { after: 200 },
          }),
          new Paragraph({
            children: [new TextRun({ text: `提交时间：${formatDateTime(report.submitTime) || '无'}`, size: 24 })],
            spacing: { after: 200 },
          }),
          new Paragraph({
            children: [new TextRun({ text: `举报人选择的标签：${formatTags(report.tags) || '无'}`, size: 24 })],
            spacing: { after: 200 },
          }),
          
          // 举报内容
          new Paragraph({
            children: [
              new TextRun({
                text: "主要反映问题：",
                bold: true,
                size: 24,
              }),
            ],
            spacing: { after: 200 },
          }),
          new Paragraph({
            children: [new TextRun({ text: report.mainIssue || '无', size: 24 })],
            spacing: { after: 400 },
          }),
          
          // 分管部门
          new Paragraph({
            children: [new TextRun({ text: `分管部门：${report.department || '无'}`, size: 24 })],
            spacing: { after: 200 },
          }),
        ],
      }],
    })

    // 生成Word文档
    const blob = await Packer.toBlob(doc)
    return blob
  } catch (error) {
    console.error('生成Word文档失败:', error)
    throw error
  }
}

// 下载单个列表项
const handleDownloadItem = async (item) => {
  // 防止重复点击
  if (downloadingItems.value[item.reportId]) {
    return
  }
  
  try {
    // 设置下载状态
    downloadingItems.value[item.reportId] = true
    ElMessage.info('正在准备下载文件，请稍候...')
    
    // 获取详细数据
    const res = await getReportDetail(item.reportId)
    if (res.code !== 200) {
      throw new Error(res.message || '获取举报详情失败')
    }
    
    const detail = res.data
    
    // 生成Word文档
    const wordDoc = await generateWordDocument(detail.report)
    
    // 如果有附件，打包成zip
    if (detail.files && detail.files.length > 0) {
      const zip = new JSZip()
      
      // 添加Word文档到zip
      zip.file(`举报详情.docx`, wordDoc)
      
      // 文件夹分类
      const folderMap = {
        'image': '图片附件',
        'video': '视频附件',
        'other': '其他附件'
      }
      
      // 下载并添加所有附件
      for (const file of detail.files) {
        try {
          // 获取文件分类文件夹
          const folderName = folderMap[file.fileType] || '其他附件'
          
          // 下载文件
          const fileData = await downloadFile(file.filePath)
          
          // 添加到对应文件夹
          zip.file(`${folderName}/${file.fileName}`, fileData)
        } catch (err) {
          console.error(`添加文件到压缩包失败: ${file.fileName}`, err)
          ElMessage.warning(`文件 ${file.fileName} 下载失败，将被跳过`)
        }
      }
      
      // 生成zip文件并下载
      const content = await zip.generateAsync({ type: 'blob' })
      saveAs(content, `举报详情_${item.reportId}_附件.zip`)
    } else {
      // 如果没有附件，只下载Word文档
      saveAs(wordDoc, `举报详情_${item.reportId}.docx`)
    }
    
    ElMessage.success('下载完成！')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败，请重试')
  } finally {
    // 清除下载状态
    downloadingItems.value[item.reportId] = false
  }
}

// 在组件挂载时获取活动数据
onMounted(async () => {
  resetFilters()  // 重置筛选条件
  await fetchData()
  tableData.value = formatTableData(tableData.value)
})

// 添加组件卸载钩子
onUnmounted(() => {
  // 清理工作
  resetFilters()  // 清理筛选条件

})

</script>

<style scoped>
@import '@/assets/css/list.css';
@import '@/assets/css/header/index.css';
@import '@/assets/css/others/pagination.css';
@import '@/assets/css/others/btn.css';
@import '@/assets/css/others/dateEditor.css';
@import '@/assets/css/others/search.css';
@import '@/assets/css/others/select.css';

</style>